package com.lgy.springboot_example.controller;

import com.lgy.springboot_example.async.AsyncManager;
import com.lgy.springboot_example.utils.DataResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

@Api(tags = "sync异步调用测试")
@RequestMapping("sync")
@RestController
public class AsyncController {

    @Autowired
    private AsyncManager sync;

    @GetMapping("syncTest")
    @ApiOperation("异步调用")
    public DataResult<Object> syncTest() {
        long begin = System.currentTimeMillis();
        sync.todo(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.currentTimeMillis();
        return new DataResult<>(1, "Controller耗时 : " + (end - begin) + " ]");
    }

    @GetMapping("syncTest2")
    @ApiOperation("有返回值的异步调用")
    public DataResult<Object> syncTest2() {
        long begin = System.currentTimeMillis();
        Future<String> task = sync.todo2(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Future<String> task2 = sync.todo2(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        while (true) {
            if (task.isDone() && task2.isDone()) break;
        }
        long end = System.currentTimeMillis();
        return new DataResult<>(1, "Controller耗时 : " + (end - begin) + " ]");
    }
}
